
clear all
set more off
set maxvar 20000
 
cd /data2/cedsei/firm/

/* Inputs */ 

local in_ana   "/data2/cedsei/firm/C1_anaprep_v2_20230608.dta"

global c_controls "i.my i.sni3 i.r_s i.r_m_djl"
global b_controls "i.my i.sni3 i.r_s i.r_m_a"
global a_controls "age cumten s_age s_ten s"

/* Outputs */

********************************************************************************
clear 
use `in_ana'

eststo clear	
qui foreach outcome in ch_prod d_prod {
	
	foreach kk of numlist 1 2 {
		reghdfe `outcome' chi m_a $a_controls if evyear==-`kk' , absorb($b_controls) vce(cluster lopnr_peorgnr)
		local s`kk'b = round(_b[chi]*1000)/1000
		matrix v=e(V) 
		local s`kk's = round(sqrt(v[1,1])*1000)/1000
	}		
	eststo: reghdfe `outcome' chi m_a $a_controls if evyear==0  , absorb($b_controls) vce(cluster lopnr_peorgnr)
	scalar b_chi=_b[chi]
	matrix v=e(V)
	scalar se_b=sqrt(v[1,1])
	quietly sum chi if evyear==0
	estadd scalar alpha3=(1-exp(b_chi*r(mean)))/r(mean)
	 scalar alpha3=(1-exp(b_chi*r(mean)))/r(mean)
	scalar se_alpha=exp(b_chi*r(mean))*se_b+(alpha3+exp(b_chi*r(mean))*b_chi)*r(sd)/r(N)
	estadd scalar se_alt=se_b/abs(b_chi)*alpha3
	estadd local ones = "-"
	estadd scalar s1b  = `s1b'
	estadd scalar s1s = `s1s'
	estadd scalar s2b  = `s2b'
	estadd scalar s2s = `s2s'
	
	foreach kk of numlist 1 2 {
		ivreg2 `outcome' (chi=chi_djl chi_djl2) m_djl $a_controls $c_controls if evyear==-`kk'  , cluster(lopnr_peorgnr) first partial($c_controls)
		local s`kk'b = round(_b[chi]*1000)/1000
		matrix v=e(V) 
		local s`kk's = round(sqrt(v[1,1])*1000)/1000
	}		
	eststo: ivreg2 `outcome' (chi=chi_djl chi_djl2) m_djl $a_controls $c_controls if evyear==0 , cluster(lopnr_peorgnr) first partial($c_controls)
	scalar b_chidj=_b[chi]
	matrix v=e(V)
	scalar se_bdj=sqrt(v[1,1])
	quietly sum chi if evyear==0
	estadd scalar alpha3 =(1-exp(b_chidj*r(mean)))/r(mean)
	scalar alpha3dj=(1-exp(b_chidj*r(mean)))/r(mean)
	scalar se_alphadj=exp(b_chidj*r(mean))*se_bdj+(alpha3dj+exp(b_chidj*r(mean))*b_chidj)*r(sd)/r(N)
	estadd scalar se_alt=se_bdj/abs(b_chidj)*alpha3dj
	scalar se_altdj=se_bdj/abs(b_chidj)*alpha3dj
	// scalar list b_chidj se_bdj alpha3dj se_alphadj se_altdj
	mat first= e(first)
	matrix list first
	estadd scalar ones = first[4,1]
	estadd scalar s1b  = `s1b'
	estadd scalar s1s = `s1s'
	estadd scalar s2b  = `s2b'
	estadd scalar s2s = `s2s'
	
}
esttab , keep(chi ) se(4) b(4) star(* 0.1 ** 0.05 *** 0.01)  stats(N alpha3 se_alt ones s1b s1s s2b s2s)
esttab using "table_firm_alpha.tex", replace cells(b(star fmt(3)) se(par fmt(3))) starlevels(* 0.1 ** 0.05 *** 0.01)  keep(chi) booktabs nodepvars noobs nomtitles stats(alpha3 se_alt ones   s1b s1s s2b s2s N  ) 


